const Sequelize = require('sequelize')
const { db: dbconfig } = require('../config/config.js')

const sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password, {
    host: dbconfig.host,
    port: dbconfig.port,
    dialect: 'mysql',
    timezone: '+08:00',
    pool: {
        max: 5,
        min: 0,
        //建立连接最长时间
        acquire: 30000,
        //空闲最长连接时间
        idle: 10000
    },
    //默认输出执行sql语句
    logging: console.log,
    define: {
        charset: 'utf8mb4',
        //表名不转复数
        freezeTableName: true,
        //默认创建表有 createAt, updateAt
        timestamps: false,
        // 字段以下划线（_）来分割（默认是驼峰命名风格）
        underscored: false
    }
})

const fs = require('fs')
const path = require('path')
const basename = path.basename(__filename)
const db = {}

fs.readdirSync(path.join(__dirname, '../schema'))
    .filter(file => {
        return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js'
    })
    .forEach(file => {
        const model = sequelize['import'](path.join(__dirname, '../schema', file))
        db[model.name] = model
    })

Object.keys(db).forEach(modelName => {
    if (db[modelName].associate) {
        db[modelName].associate(db)
    }
})

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db
